/**
 * Create by yxk at 2020/5/29
 */
import SlideView from '@/components/SlideView'
import DetailHeader from '../components/DetailHeader'

import TabBaseInfo from '../components/DetailTab/TabBaseInfo' // 基本信息
import TabFile from '../components/DetailTab/TabFile' // 附件
import TabRecordList from '../components/DetailTab/TabRecordList' // 操作记录

import JxcTypes from '../jxcTypes'
// import jxcExamineLib from '../jxcExamineStatus'
// import { isEmpty } from '@/utils/types'
import { objDeepCopy } from '@/utils'
import { mapGetters } from 'vuex'

export default {
  components: {
    SlideView,
    DetailHeader,

    TabBaseInfo,
    TabFile,
    TabRecordList
  },
  props: {
    // 监听的dom 进行隐藏详情
    listenerIDs: {
      type: Array,
      default: () => {
        return ['crm-main-container']
      }
    },
    // 不监听
    noListenerIDs: {
      type: Array,
      default: () => {
        return []
      }
    },
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    },
    // 详情ID
    id: {
      type: [String, Number],
      required: true
    },
    // 进销存类型
    type: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      detailData: {},
      examineInfo: null, // 审批信息

      copyBtnGroup: null, // 拷贝初始操作按钮
      copyMoreBtnGroup: null, // 拷贝初始更多操作按钮

      isDeleted: false
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'jxc']),

    typeObj() {
      return JxcTypes[this.type]
    },
    showExamine() {
      if (['jxc_receipt', 'jxc_outbound'].includes(this.type)) return false
      return !!this.detailData.recordId
    },

    canShowDetail() {
      if (this.isDeleted) return false
      const type = this.type.replace('jxc_', '')
      return this.jxc && this.jxc[type] && this.jxc[type].read
    }
  },
  watch: {
    id: {
      handler() {
        if (this.id && this.getDetail) {
          this.getDetail()
        }
      },
      immediate: true
    },
    jxc: {
      handler(val) {
        if (!val) return
        this.checkBtnAuth()
      },
      deep: true
    }
  },
  created() {
    this.copyBtnGroup = objDeepCopy(this.btnGroup || [])
    this.copyMoreBtnGroup = objDeepCopy(this.moreBtnGroup || [])
    this.checkBtnAuth()
  },
  methods: {
    /**
     * 操作按钮鉴权
     */
    checkBtnAuth() {
      const val = this.jxc
      if (!val || !this.type) return
      const authBtn = ['update', 'setState', 'delete', 'transfer', 'self', 'save']
      const type = this.type.replace('jxc_', '')
      authBtn.forEach(command => {
        const auth = val[type] ? val[type][command] || false : false
        let findIndex = this.copyBtnGroup.findIndex(o => o.command === command)
        if (findIndex !== -1 && !auth) {
          this.copyBtnGroup.splice(findIndex, 1)
        }
        findIndex = this.copyMoreBtnGroup.findIndex(o => o.command === command)
        if (findIndex !== -1 && !auth) {
          this.copyMoreBtnGroup.splice(findIndex, 1)
        }
      })
      this.renderControlBtn()
    },
    /**
     * 获取详情
     */
    getDetail() {
      if (!this.detailRequest) return
      this.loading = true
      this.detailData = {}
      this.detailRequest({
        id: this.id,
        label: this.typeObj.label
      }).then(res => {
        this.loading = false
        if (res.data === null || res.data.isDel == 1) {
          this.isDeleted = true
          this.$message.error('已经被删除，无法查看详情')
          this.hideView()
          return
        }
        this.detailData = res.data || {}

        // 调拨审核通过后，即使是管理员也禁止删除，强制设置为非超管
        if (this.type === 'jxc_allocation') {
          delete this.detailData.isAdmin
        }
        if (this.detailData.hasOwnProperty('state')) {
          this.checkBtnAuth()
        }

        console.log('detail res', res)
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 记录审批流信息
     * @param data
     */
    handleExamineInfo(data) {
      this.examineInfo = data || null
      this.renderControlBtn()
    },

    renderControlBtn() {
      const state = Number(this.detailData.state)
      const btnGroup = objDeepCopy(this.copyBtnGroup)
      const moreBtnGroup = objDeepCopy(this.copyMoreBtnGroup)
      if (['jxc_supplier', 'jxc_product'].includes(this.type)) {
        this.btnGroup = btnGroup
        this.moreBtnGroup = moreBtnGroup
        return
      }

      // 审核拒绝  审核撤回 未提交 才能编辑
      let findIndex = btnGroup.findIndex(o => o.command === 'update')
      if (findIndex !== -1 && this.detailData.hasOwnProperty('state')) {
        if (![1, 7, 8].includes(state)) {
          btnGroup.splice(findIndex, 1)
        }
      }

      // 撤回状态下可以删除。 超管一直都可删除
      findIndex = moreBtnGroup.findIndex(o => o.command === 'delete')
      if (findIndex !== -1 &&
        !this.detailData.isAdmin &&
        this.detailData.hasOwnProperty('state')) {
        if (state !== 7) {
          moreBtnGroup.splice(findIndex, 1)
        }
      }

      // 审核通过，有作废权限才能作废合同
      findIndex = moreBtnGroup.findIndex(item => item.command === 'setState')
      if (findIndex !== -1 && this.detailData.hasOwnProperty('state')) {
        if (![3, 4, 5].includes(state)) {
          moreBtnGroup.splice(findIndex, 1)
        }
      }
      this.btnGroup = btnGroup
      this.moreBtnGroup = moreBtnGroup
    },

    /**
     * 作废
     */
    handleInvalid() {
      if (!this.invalidRequest) return
      this.$confirm(`确定要作废这该${this.typeObj.name}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.invalidRequest({
          ids: this.detailData[this.typeObj.primaryKey]
        }).then(() => {
          this.$message.success('作废成功')
          this.handleRefresh()
          this.handleUpdateList()
        }).catch(() => {})
      }).catch(() => {
        this.$message.info('已取消')
      })
    },

    /**
     * 删除
     */
    handleDelete() {
      if (!this.deleteRequest) return
      this.$confirm(`确定要删除该${this.typeObj.name}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest({
          ids: this.id
        }).then(() => {
          this.$message.success('删除成功')
          this.handleUpdateList()
          this.hideView()
        }).catch(() => {})
      }).catch(() => {
        this.$message.info('已取消')
      })
    },

    hideView() {
      console.log('hidden view')
      this.$emit('close')
    },

    handleRefresh() {
      this.getDetail()
      this.handleUpdateList()
    },

    handleUpdateList() {
      this.$emit('update')
    }
  }
}
